package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * 菜品管理
 */
@RestController
@RequestMapping("dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 按条件分页查询菜品
     * @param curPage
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("page")
    public R<Page<DishDto>> queryDishPage(@RequestParam("page") Integer curPage,
                                       Integer pageSize, String name) {
//        if (name !=null) { name = name.trim();}
        Page<DishDto> page = dishService.queryDishDtoPage(curPage, pageSize, name);
        return R.success(page);
    }

    /**
     * 根据菜品id查询菜品和菜品口味
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> queryDishById(@PathVariable Long id) {
        // 嵌套查询
//        DishDto dishDto = dishService.queryDishDtoById(id);
        // 连接查询
        DishDto dishDto = dishService.queryDishDtoByDishId(id);
        return R.success(dishDto);
    }

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)
    public R<String> addDishDto(@RequestBody DishDto dishDto) {
        if(dishDto.getFlavors() == null) {
            return R.error("菜品的口味数据错误");
        }
        dishService.addDishDto(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)
    public R<String> updateDishDto(@RequestBody DishDto dishDto) {
        if(dishDto.getFlavors() == null) {
            return R.error("菜品的口味数据错误");
        }
        dishService.updateDishDto(dishDto);
        return R.success("菜品修改成功");
    }

//    public R updateDishHandleFlavor(@RequestBody DishDto dishDto, HttpSession session) {
//        // 查询菜品id对应的原有口味
//        List<DishFlavor> dishFlavors = dishFlavorService.queryDishFlavorByDishId(dishDto.getId());
//        Set<DishFlavor> dishFlavorSet = new HashSet<>(dishFlavors);
//        // 菜品修改后的口味
//        List<DishFlavor> flavors = dishDto.getFlavors();
//        Set<DishFlavor> flavorSet = new HashSet<>(flavors);
//        return null;
//    }

    /**
     * 修改菜品状态status
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("status/{status}")
    @CacheEvict(cacheNames = "dish", allEntries = true)
    public R<String> batchUpdateDishStatus(@PathVariable Integer status, Long[] ids) {
        // 菜品是否关联套餐、购物车、订单详情
        dishService.lambdaUpdate()
                .set(Dish::getStatus, status)
                .set(Dish::getUpdateTime, LocalDateTime.now())
                .set(Dish::getUpdateUser, BaseContext.getCurrentId())
                .in(Dish::getId, Arrays.asList(ids))
                .update();
        return R.success("菜品状态修改成功");
    }

    /**
     * 删除菜品以及菜品对应的口味
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(cacheNames = "dish", allEntries = true)
    public R<String> batchDeleteDishDto(Long[] ids) {
//        String[] split = ids.split(",");
//        List<Long> dishIds = Stream.of(split).map(Long::parseLong)
//                                             .collect(Collectors.toList());
        List<Long> dishIds = Arrays.asList(ids);
        dishService.batchDeleteDishDto(dishIds);
        return R.success("删除菜品成功");
    }

//    @Autowired
//    private CacheManager cacheManager;
    /**
     * 查询分类下的所有起售菜品
     * @param categoryId
     * @return
     */
    @GetMapping("list")
    @Cacheable(cacheNames = "dish", key = "#categoryId + '_' + #name", unless = "#result.data.size()<=0")
    public R<List<DishDto>> queryDishDtoList(Long categoryId, String name ,Integer status) {
//        List<Dish> dishes = dishService.lambdaQuery()
//                .eq(status !=null, Dish::getStatus, 1) // 只查询起售的菜品
//                .eq(categoryId != null, Dish::getCategoryId, categoryId)
//                .like(StringUtils.isNotBlank(name), Dish::getName, name)
//                .list();
        if (status == null) {
            status = 1;
        }
        List<DishDto> dishDtoList = dishService.queryDishDtoList(categoryId, name, status);
        return R.success(dishDtoList);
    }
}
